<template>
	<view>
		<view class="top-bar u-f-jsb">
			<view class="u-f-ac">
				<image
					style="width: 36rpx;height: 36rpx;"
					src="/static/images/icon-area-sel.png"
					mode="widthFix"
				></image>
				<ym-region @change="handelRegion"></ym-region>
			</view>
			<view @tap="$jumpPage('/pages/siteMap/siteMap')">
				<text>地图分布</text>
				<u-icon name="arrow-right"></u-icon>
			</view>
		</view>

		<view class="site-list">
			<view v-if="taskMsgs.length" class="msg-box">
				<view
					class="msg"
					v-for="(item, index) in taskMsgs"
					:key="index"
					@tap="$jumpPage('/pages/msgDetail/msgDetail')"
				>
					<text v-if="item.status === 'doing'">当前有一项补液任务正在进行</text>
					<text v-else>当前有一项补液任务已完成</text>
					<text class="c-blue">{{ item.status === 'doing' ? '查看' : '确认' }}</text>
				</view>
			</view>
			<block v-for="(site, index) in siteList" :key="site.id">
				<view
					class="site-item animated fadeInUp"
					:class="'item'+index"
					:data-item="index"
					:animation="animationDatas[index]"
				>
					<view class="title u-f-jsb">
						<view class="title-l">
							<view>{{ site.siteName }} {{index}}</view>
							<view>{{ site.siteAddress }}</view>
						</view>
						<view class="title-r u-f-ac" @tap="gotoMap(site)">
							<u-icon name="map"></u-icon>
							<text>{{ site.distance }}km</text>
						</view>
					</view>
					<view class="bucket-list">
						<template v-if="site.machineOrBucket.length">
							<block
								v-for="(bucket, subIndex) in site.machineOrBucket"
								:key="bucket.id"
							>
								<view class="bucket u-f-jsb">
									<view class="bucket-l">
										<view class="name">
											编号：{{ bucket.macCode || bucket.deviceName }}
										</view>
			
										<view class="info">
											<view>
												桶容量：{{
													(bucket.totalCapacity ||
														bucket.totalWeight) | kg2ton
												}}吨
											</view>
											<view class="u-f-ac ">
												余量：
												<u-count-to
													v-if="bucket.supplyAmount"
													:start-val="bucket.actualRestWeight / 1000"
													:end-val="
														(bucket.actualRestWeight +
															bucket.supplyAmount || 0) | kg2ton
													"
													:duration="1500"
													:use-easing="false"
													decimals="3"
													font-size="30"
													:autoplay="bucket.supplyAmount"
													@end="handleCountEnd(bucket)"
												></u-count-to>
												<view v-else>
													{{ bucket.actualRestWeight | kg2ton }}
												</view>
												吨
												<view
													v-if="bucket.supplyAmount"
													class="fadeInUp"
												>
													+{{ bucket.supplyAmount | kg2ton }}吨
												</view>
											</view>
			
											<view>
												传感器余量：
												<text v-if="bucket.iotRestWeight">
													{{ bucket.iotRestWeight | kg2ton }}
												</text>
												<text v-else>---</text>
											</view>
										</view>
									</view>
									<view
										class="btn-supply"
										@tap="jumpPage({ bucket, index, subIndex })"
									>
										补液
									</view>
								</view>
							</block>
						</template>
						<template v-else>
							<view class="u-f-ajc no-info">暂无库存信息</view>
						</template>
					</view>
				</view>
			</block>
		</view>

		<u-loadmore margin-bottom="30" icon-color="#00a1f1" :status="status" />
		<view class="bottom-bar"></view>
	</view>
</template>

<script>
import ymRegion from '@/components/ym-region/ym-region.vue';
import siteCard from '@/components/site-card/site-card.vue';
import { mapDistance, convert2TecentMap } from '@/common/utils.js';
export default {
	components: { ymRegion, siteCard },
	data() {
		return {
			siteList: [],
			status: 'loading', // loadmore|loading|nomore
			renderIndex: 6,
			listData: [], // 数组数据
			tapIndexs: [0, 0],
			animationDatas: []
		};
	},
	computed: {
		taskMsgs() {
			return this.$store.state.taskMsgs;
		},
		myPos() {
			return this.$store.state.myPos;
		}
	},
	onLoad() {
		
		this.$store.dispatch('getMyLocation');
		this.page = 1;
		let regions = uni.getStorageSync('regions');
		this.areaId = regions.areaId || '';
		this.areaType = regions.areaType || '';
		uni.$on('locationGet', this.getSiteList);
		// 补液完成，首页数据刷新
		uni.$on('supplyFinished', data => {
			const { supplyAmount } = data;
			let site = this.siteList[this.tapIndexs[0]];
			site.machineOrBucket[this.tapIndexs[1]].supplyAmount = supplyAmount;
			this.siteList.splice(this.tapIndexs[0], 1, site);
		});
	},
	onReady() {
		
	}, 
	onPullDownRefresh() {
		this.siteList.length = 0;
		this.page = 1;
		this.getSiteList();
		setTimeout(() => {
			uni.stopPullDownRefresh();
			this.$forceUpdate();
		}, 888);
	},
	onReachBottom() {
		console.log('到底了');
		if (this.status === 'nomore') return;
		this.page++;
		this.limit = 5;
		this.getSiteList();
		this.observe.disconnect()
		
	},
	onUnload() {
		uni.$off('locationGet');
		uni.$off('supplyFinished');
	},
	methods: {
		handleCountEnd(bucket) {
			console.log(bucket);
			let site = this.siteList[this.tapIndexs[0]];
			site.machineOrBucket[this.tapIndexs[1]].actualRestWeight += bucket.supplyAmount;
			delete site.machineOrBucket[this.tapIndexs[1]].supplyAmount;
			this.siteList.splice(this.tapIndexs[0], 1, site);
			this.tapIndexs = [];
		},
		getSiteList() {
			const { areaId = '', areaType = '', page } = this;
			this.$u.api._getSiteList({ areaId, areaType, page, limit: this.limit||6}).then(res => {
				let sites = res.data;
				sites.forEach((item,index) => {
					item = convert2TecentMap(item);
					item.distance = mapDistance(
						this.myPos.latitude,
						this.myPos.longitude,
						item.siteLat,
						item.siteLng
					);
					
				});
				this.siteList = [...this.siteList, ...sites];
				this.status = 'loadmore';
				if (res.count <= this.siteList.length) {
					this.status = 'nomore';
				}
				this.$nextTick(function(){
					this.observe = uni.createIntersectionObserver(this, { observeAll: true });
					this.observe.relativeTo('.bottom-bar',{ bottom: 0 }).observe(`.site-item`, res => {
						console.log(res.dataset);
						let item = res.dataset.item;
						if( res.intersectionRatio===0){
							console.log(res.dataset.item,'离开底部');
						}
						var animation = uni.createAnimation({
							duration: 1000,
							timingFunction: 'ease',
							delay: 0
						});
						animation
							.translateY(0)
							.opacity(1)
							.step();
						this.animationDatas[item+1] = animation.export()
					});
				})
			});
		},
		handelRegion(arr) {
			console.log(arr);
			let obj = arr[1];
			this.areaId = obj.id;
			this.areaType = obj.level;
			if (obj.name === '全部') {
				this.areaType = 1;
			}
			if (obj.name === '全国') {
				this.areaType = '';
				this.areaId = '';
			}
			this.siteList = [];
			this.getSiteList();
		},
		jumpPage({ bucket, index, subIndex }) {
			this.tapIndexs = [index, subIndex];
			if (bucket.deviceName) {
				uni.navigateTo({
					url:
						`/pages/supplying/supplying?site=` +
						encodeURIComponent(JSON.stringify(bucket))
				});
			} else {
				uni.navigateTo({
					url:
						`/pages/supplying/noSensor?site=` +
						encodeURIComponent(JSON.stringify(bucket))
				});
			}
		},
		gotoMap(site) {
			if (site.machineOrBucket.length) {
				delete site.machineOrBucket;
				uni.navigateTo({
					url: '/pages/siteMap/siteMap?site=' + encodeURIComponent(JSON.stringify(site))
				});
			}
		}
	}
};
</script>

<style lang="scss">
@keyframes slidein {
	0% {
		opacity: 0;
		transform: translateY(100rpx) scale(0.96);
	}
	40% {
		opacity: 0.88;
	}
	100% {
		opacity: 1;
		transform: translateY(0rpx) scale(1);
	}
}

@keyframes fadeInUp {
	0% {
		opacity: 1;
		transform: translateY(-60rpx) scale(1.1);
	}
	40% {
		opacity: 0.88;
	}
	100% {
		opacity: 0;
		transform: translateY(0) scale(1);
	}
}

page {
	// background-color: #f0f0f0;
	background-color: #fff;
}

.top-bar {
	background-color: #ffffff;
	padding: 0 30rpx;
	border-top: 1rpx solid #eee;
	border-bottom: 1rpx solid #eee;
	height: 100rpx;
	position: fixed;
	top: 0;
	width: 100vw;
	z-index: 999;
}
.bottom-bar {
	position: fixed;
	bottom: 0;
	width: 100vw;
	height: 10rpx;
	background-color: red;
}
.c-blue {
	color: $uni-color-primary;
}
.no-info {
	color: #808080;
	margin: 30rpx 0;
}

.site-list {
	margin-top: 100rpx;
	padding: 20rpx;
	.msg-box {
		margin-bottom: 10rpx;
		z-index: 999;

		.msg {
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 16rpx;
			background-color: #ffffff;
			margin-bottom: 10rpx;
			margin: 10rpx 0;
			border-radius: 10rpx;
			box-shadow: 0 0 6px 1rpx rgba(0, 0, 0, 0.1);
		}
	}
	.site-item {
		border-radius: 16rpx;
		background-color: #ffffff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		transform: translateY(100rpx);
		box-shadow: 0 0 6px 1rpx rgba(0, 0, 0, 0.1);
		opacity: 0;
		// animation: ease-in 0.66s slidein;

		.title {
			border-bottom: 1rpx solid #eee;
			padding-bottom: 10rpx;
			.title-l {
				flex: 1;
				flex-shrink: 0;
				overflow: hidden;
				& > view:nth-child(1) {
					font-weight: 800;
					font-size: 32rpx;
					margin-bottom: 10rpx;
				}
				& > view:nth-child(2) {
					font-size: 28rpx;
					color: #808080;
				}
			}
			.title-r {
				width: 200rpx;
				justify-content: flex-end;
				font-weight: 600;
				color: $uni-color-primary;
			}
		}

		.bucket {
			padding: 10rpx 0;
			padding-bottom: 20rpx;
			.bucket-l {
				flex: 1;
				flex-shrink: 0;
				overflow: hidden;
				margin-right: 10rpx;
				.name {
					color: #333333;
					font-size: 32rpx;
					margin-bottom: 10rpx;
					font-weight: 600;
				}
				.info {
					display: inline-flex;
					flex-wrap: wrap;
					> view {
						position: relative;
						font-size: 28rpx;
						margin-right: 20rpx;
						color: #808080;
						height: 40rpx;

						.fadeInUp {
							position: absolute;
							color: $uni-color-primary;
							font-weight: 800;
							right: 0rpx;
							opacity: 0;
							animation: ease-in 1.5s fadeInUp;
						}
					}
				}
			}
			.btn-supply {
				align-self: flex-end;
				width: 120rpx;
				height: 50rpx;
				line-height: 50rpx;
				border-radius: 25rpx;
				text-align: center;
				background-color: $uni-color-primary;
				color: #ffffff;
			}
		}
	}
}
</style>
